<template>
  <div class="login-wrap">
    <el-form
      label-position="left"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="0px"
      class="demo-ruleForm login-container"
    >
      <h3 class="title">企业考勤系统</h3>
      <el-form-item prop="uid">
        <el-input
          type="text"
          v-model="ruleForm.uid"
          auto-complete="off"
          placeholder="账号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          auto-complete="off"
          placeholder="密码"
        ></el-input>
      </el-form-item>
      <!-- 验证码 -->
      <el-row>
        <el-col :span="12">
          <el-form-item prop="code">
            <el-input
              type="text"
              v-model="inputCode"
              placeholder="验证码"
              auto-complete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="code-box">
          <canvas class="codeCanvas" ref="checkCode" @click="getcode"> </canvas>
        </el-col>
      </el-row>
      <el-checkbox class="remember" v-model="rememberpwd">记住密码</el-checkbox>
      <el-form-item style="width: 100%">
        <el-button
          type="primary"
          style="width: 100%"
          @click="submitForm('ruleForm')"
          :loading="logining"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script type="text/ecmascript-6">
import { login } from "../../api/userMG";
import { setCookie, getCookie, delCookie } from "../../utils/util";
import md5 from "js-md5";
export default {
  name: "login",
  data() {
    return {
      //定义loading默认为false
      logining: false,
      // 记住密码
      rememberpwd: false,
      ruleForm: {
        //uid和password默认为空
        uid: null,
        password: "",
      },
      //rules前端验证
      rules: {
        uid: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        // code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      // 验证码
      inputCode: "", // 输入的值
      checkCode: "", // 图片验证码的值
      expressValue: "", // 表达式的值
      // canvas各种设置
      cvs: {
        w: 300, // 给出默认宽度  宽度会在图片绘制时根据长度更改
        h: 40, // 高 与input保持一致
        fontSize: 24, // 字体大小
        str: "+-*", // 符号生成范围
        line: 3, // 噪音线个数
      },
    };
  },
  // 创建完毕状态(里面是操作)
  created() {
    // 获取存在本地的用户名密码
    this.getuserpwd();
  },
  // 里面的函数只有调用才会执行
  methods: {
    // 获取用户名密码
    getuserpwd() {
      if (getCookie("user") != "" && getCookie("pwd") != "") {
        this.ruleForm.uid = getCookie("user");
        this.ruleForm.password = getCookie("pwd");
        this.rememberpwd = true;
      }
    },
    //获取info列表
    submitForm(formName) {
      if (this.inputCode) {
        // eslint-disable-next-line no-eval
        if (eval(this.inputCode) === eval(this.expressValue)) {
        } else {
          // 验证码有误
          this.$message.error("验证码输入错误！");
          return;
        }
      } else {
        // 输入为空
        this.$message.error("请输入图中算式的结果");
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.logining = true;
          login(this.ruleForm).then((res) => {
            if (res.code == 200) {
              window.sessionStorage.setItem("uid", this.ruleForm.uid);
              if (this.rememberpwd) {
                window.sessionStorage.setItem("pwd", this.ruleForm.password);
                //保存帐号到cookie，有效期7天
                setCookie("user", this.ruleForm.uid, 7);
                //保存密码到cookie，有效期7天
                setCookie("pwd", this.ruleForm.password, 7);
              } else {
                window.sessionStorage.removeItem("pwd");
                delCookie("user");
                delCookie("pwd");
              }
              //如果请求成功就让他2秒跳转路由
              setTimeout(() => {
                this.logining = false;
                // 缓存用户个人信息
                localStorage.setItem("userdata", JSON.stringify(res.data));
                this.$store.commit("login", "true");
                if (res.data.identity == "admin") {
                  this.$router.push({ path: "/admin" });
                } else if (res.data.identity == "user") {
                  this.$router.push({ path: "/usr" });
                }
              }, 1000);
            } else {
              this.$message.error(res.msg);
              this.logining = false;
              return false;
            }
          });
        } else {
          // 获取图形验证码
          this.getcode();
          this.$message.error("请输入用户名密码！");
          this.logining = false;
          return false;
        }
      });
    },
    getcode() {
      let domCvs = this.$refs.checkCode;
      this.drawCode(domCvs);
    },
    // canvas
    // 随机整数生成器，范围[0, max)
    rInt(max) {
      return Math.floor((Math.random() * 100000) % max);
    },
    // 生成随机表达式
    rCode() {
      let a = this.rInt(100);
      let b = this.rInt(10);
      let op = this.cvs.str.charAt(this.rInt(this.cvs.str.length));
      // 表达式
      let code = `${a}${op}${b}=`;
      this.checkCode = code;
      // 表达式的值
      // eslint-disable-next-line no-eval
      this.expressValue = eval(code.substr(0, code.length - 1));
      return code;
    },
    // 生成随机颜色 rgba格式
    rColor() {
      let a = ((Math.random() * 5 + 5) / 10).toFixed(2);
      return `rgba(${this.rInt(256)}, ${this.rInt(256)}, ${this.rInt(
        256
      )}, ${a})`;
    },
    // 验证码图片绘制
    drawCode(domCvs) {
      let _this = this;
      // 随机表达式
      let checkCode = this.rCode();
      // 宽设置
      this.cvs.w = 10 + this.cvs.fontSize * this.checkCode.length;
      // 判断是否支持canvas
      if (domCvs !== null && domCvs.getContext && domCvs.getContext("2d")) {
        // 设置显示区域大小
        domCvs.style.width = _this.cvs.w;
        // 设置画板宽高
        domCvs.setAttribute("width", _this.cvs.w);
        domCvs.setAttribute("height", 60);
        // 画笔
        let pen = domCvs.getContext("2d");
        // 背景: 颜色  区域
        pen.fillStyle = "#eee";
        pen.fillRect(0, 10, _this.cvs.w, _this.cvs.h);
        // 水平线位置
        pen.textBaseline = "middle"; // top middle bottom
        // 内容
        for (let i = 0; i < _this.checkCode.length; i++) {
          pen.fillStyle = _this.rColor(); // 随机颜色
          pen.font = `bold ${_this.cvs.fontSize}px 微软雅黑`; // 字体设置
          // 字符绘制: (字符, X坐标, Y坐标)
          pen.fillText(
            checkCode.charAt(i),
            10 + _this.cvs.fontSize * i,
            30 + _this.rInt(10)
          );
        }
        // 噪音线
        for (let i = 0; i < _this.cvs.line; i++) {
          // 起点
          pen.moveTo(_this.rInt(_this.cvs.w) / 2, _this.rInt(_this.cvs.h) + 10);
          // 终点
          pen.lineTo(_this.rInt(_this.cvs.w), _this.rInt(_this.cvs.h) + 10);
          // 颜色
          pen.strokeStyle = _this.rColor();
          // 粗细
          pen.lineWidth = "2";
          // 绘制
          pen.stroke();
        }
      } else {
        this.$message.error("不支持验证码格式，请升级或更换浏览器重试");
      }
    },
  },
};
</script>

<style scoped>
.login-wrap {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding-top: 10%;
  background-image: url();
  /* background-color: #112346; */
  background-repeat: no-repeat;
  background-position: center right;
  background-size: 100%;
}
.login-container {
  border-radius: 10px;
  margin: 0px auto;
  width: 350px;
  padding: 30px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  text-align: left;
  box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
}
.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}
.remember {
  margin: 0px 0px 35px 0px;
}
.code-box {
  text-align: center;
}
.codeCanvas {
  height: 100%;
}
</style>